package liujinliang.natappvip.cc.componentdiv.view;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.ViewGroup;

import java.sql.Time;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.LogRecord;

/**
 * 在自定义 ViewGroup 必须要实现的方法有
 * 测量：onMeasure()
 * 布局：onLayout()
 * 绘制：
 * 事件：onInterceptTouchEvent() --> onTouchEvent()
 */
public class ImageBannerViewGroup extends ViewGroup {

    // the width of child view
    private int childViewWidth;

    // the cordinateX when user pressed down
    private int downX;

    // the index of image
    private int index;

    // clickable or moveable
    private boolean isClick = false;

    // the click listener
    private ImageBannerClickListener imageBannerClickListener;

    // export the click listener's getter and setter
    public ImageBannerClickListener getImageBannerClickListener() {
        return imageBannerClickListener;
    }

    public void setImageBannerClickListener(ImageBannerClickListener imageBannerClickListener) {
        this.imageBannerClickListener = imageBannerClickListener;
    }

    public interface ImageBannerClickListener {
        void clickListener(int pos);
    }

    // TaskTimer + Timer + Handler
    private boolean isAuto = true;
    private TimerTask task;
    private Timer timer = new Timer();
    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    int recucleIndex = ++index % getChildCount();
                    scrollTo(recucleIndex * childViewWidth, 0);
                    break;
                default:
                    break;
            }
            return false;
        }
    });

    private void startAuto() {
        isAuto = true;
    }

    private void stopAuto() {
        isAuto = false;
    }

    public ImageBannerViewGroup(Context context) {
        super(context);
        initAuto();
    }

    public ImageBannerViewGroup(Context context, AttributeSet attrs) {
        super(context, attrs);
        initAuto();
    }

    public ImageBannerViewGroup(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initAuto();
    }

    /**
     * 初始化自动轮播
     */
    private void initAuto() {
        task = new TimerTask() {
            @Override
            public void run() {
                if (isAuto) {
                    handler.sendEmptyMessage(0);
                }
            }
        };
        timer.schedule(task, 5000, 1000);
    }

    /**
     * @param ev
     * @return
     * true: 交给 onTouchEvent() 方法处理事件
     * false:继续向下传递
     */
    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        return true;
    }

    /**
     * 轮播图的手动轮播处理，方式有两种
     * 1、利用 scrollTo, scrollBy 方法
     * 2、利用 Scroller 对象
     * @param event
     * @return
     * true:告诉父View，该事件已经被处理
     */
    @Override
    public boolean onTouchEvent(MotionEvent event) {

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN :
                // set up the click
                isClick = true;
                // stop auto
                stopAuto();
                // set up the downX
                downX = (int) event.getX();
                break;
            case MotionEvent.ACTION_MOVE :
                // set up the click
                isClick = false;
                // set up the moveX
                int moveX = (int) event.getX();
                // generate the effect of sliding by scrollBy()
                scrollBy(-(moveX - downX), 0);
                // reset downX currently
                downX = moveX;
                break;
            case MotionEvent.ACTION_UP :
                // start auto
                startAuto();
                // This is the left edge of the displayed part of your view.
                int scrollX = getScrollX();
                // locate the image to be showed by scrollTo()
                index = (scrollX + childViewWidth / 2) / childViewWidth;
                // handle other cases
                if (index < 0) {
                    index = 0;
                } else if (index > getChildCount() - 1) {
                    index = getChildCount() - 1;
                }
                if (isClick) {
                    // click event callback
                    imageBannerClickListener.clickListener(index);
                } else {
                    // locate the image to be showed by scrollTo()
                    scrollTo(index * childViewWidth, 0);
                }

                break;
            default:
                break;
        }

        return true;
    }

    /**
     * measure ourselves, this should set the measured dimension flag back
     * @param widthMeasureSpec
     * @param heightMeasureSpec
     */
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        // set up the width of child view
        childViewWidth = getChildAt(0).getMeasuredWidth();
        // get the size of child view
        if (getChildCount() == 0) {
            setMeasuredDimension(0, 0);
        } else {
            // measure children with constraint from parent
            measureChildren(widthMeasureSpec, heightMeasureSpec);
            // measure ourselves
            setMeasuredDimension(
                    getChildAt(0).getMeasuredWidth() * getChildCount(),
                    getChildAt(0).getMeasuredHeight());
        }
    }

    /**
     * 继承 ViewGroup 必须要实现 onLayout() 方法
     * @param changed
     * @param l
     * @param t
     * @param r
     * @param b
     */
    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        if (changed) {
            for (int i = 0; i < getChildCount(); i++) {
                getChildAt(i).layout(
                        i * getChildAt(i).getMeasuredWidth(),
                        0, (i + 1) * getChildAt(i).getMeasuredWidth(),
                        getChildAt(i).getMeasuredHeight());
            }
        }
    }
}
